package com.sensePlusVR.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.sensePlusVR.base.BaseActivity;
import com.sensePlusVR.bean.GameItem;
import com.sensePlusVR.db.ImageLibrary;
import com.sensePlusVR.db.ImageLibrary.Callback;
import com.sensePlusVR.main.R;
import com.sensePlusVR.manager.CommendItemManager;
import com.sensePlusVR.manager.DataCenter;
import com.sensePlusVR.manager.EventListener;
import com.sensePlusVR.utils.DateTimeUtil;
import com.sensePlusVR.utils.DensityUtil;
import com.sensePlusVR.utils.EventBusUtils;
import com.sensePlusVR.utils.MyDialogUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.widget.dialog.VideoDetailDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author: Loren
 * @create: 2016-7-26下午1:25:18
 * @desc:
 *1.item点击事件直接传递对象给fragment，如果想要得到position 则点击回调需要卸载onBindViewHolder中...
 *        http://www.open-open.com/lib/view/open1461909269514.html
 *        
 *2.当第一次网络数据获取慢导致首界面显示空白参照：
 * http://www.jianshu.com/p/c090ec158fc5        
 *
 */
@SuppressLint("UseSparseArrays")
@SuppressWarnings({ "unused"})
public class GameListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

	private static final String TAG = GameListAdapter.class.getSimpleName();
	private List<GameItem> gameList;
	private Context context;
	//private List<CommendItem> commendItemList = new ArrayList<CommendItem>();
	//private Map<Integer, CommendItem> commendMap = new HashMap<Integer, CommendItem>();
	private Map<Integer,ViewHolders> viewHolderMap = new HashMap<Integer,ViewHolders>();

	private DataCenter dataCenter;
	private static final int ACTION_DOWN = 1;
	private static final int ACTION_UP = 2;

	private final String KEY = this.getClass().getSimpleName();
	
	private VideoDetailDialog videoDetailDialog;
	
	public static final int TYPE_EMPTY = -1;
	public static final int TYPE_HEADER = 0;
	public static final int TYPE_NORMAL = 1;
	private View mHeaderView;
	
	public void setHeaderView(View headerView) {
		mHeaderView = headerView;
		if(ishaveHeader()){
			notifyDataSetChanged();
		}
	}

	public View getHeaderView() {
		return mHeaderView;
	}
	
	public boolean ishaveHeader(){
		return mHeaderView == null?false:true;
		
	}
	
	EventListener listener = new EventListener() {

		@Override
		public void Notify(int event, Object data, Object params) {
			// TODO Auto-generated method stub
			if (params == null || data == null)
				return;
			
			MyLog.d(TAG, "listener event : " + event);
			
			GameItem gitem = null;
//			if (event == CommendItemManager.EventCommendGot) {
//				gitem = (GameItem) data;
//			} else
				if (event == CommendItemManager.EventCommendChanaged) {
				gitem = (GameItem) data;
			}else{
				return;
			}
			if(gitem == null)return;
			//commendMap.put(citem.getId(), citem);
			//MyLog.e(TAG, "gameId="+citem.getId()+ " commend="+citem.getUp());
			ViewHolders holder = viewHolderMap.get(gitem.getId());
			if (holder != null && holder.getGameId() == gitem.getId()){
				MyLog.d(TAG, "holder != null");
				updateCommend(holder, gitem);
			}else{
				MyLog.d(TAG, "holder == null");
			}
		}

	};

	void updateCommend(final ViewHolders holder, final GameItem gitem){
		MyLog.d(TAG,"updateCommend gameItem : " + gitem);
		((BaseActivity) context).runOnUiThread(new Runnable() {
			@Override
			public void run() {
//				String uped = String.valueOf(gitem.getPraisecount());
//				int userAction = gitem.getIsPraise();
//				//holder.detail_favour_tv.setText(uped);
//				//更新列表中Item最新赞信息
//				if (userAction == 0) {
//					//holder.detail_favour_iv.setImageResource(R.drawable.favour_game);
//				} else if (userAction == 1) {
//					//holder.detail_favour_iv.setImageResource(R.drawable.favour_game);
//				}
				gameList.set(holder.getMyPosition(),gitem);
				notifyItemChanged(holder.getMyPosition());
			}
		});
	}
	
	public GameListAdapter(Context context,
			List<GameItem> gameList/* ,List<Integer> idsList */) {
		this.context = context;
		this.gameList = gameList;
		dataCenter = DataCenter.getInstans();
		dataCenter.addCommendEventListener(listener, this, KEY);
//		if (gameList != null) {
//			for (GameItem item : gameList) {
//				CommendItem ci = getGameCommend(item.getId());
//				if (ci == null) {
//					ci = new CommendItem();
//					ci.setId(item.getId());
//				}
//				commendMap.put(item.getId(), ci);
//			}
//		}
	}

	@Override
	public int getItemCount() {
		//MyLog.d(TAG, "getItemCount : " + gameList.size());
		//return gameList.size()>0?gameList.size():3;
		//return mHeaderView == null ? gameList.size() :gameList.size() + 1;
		return gameList.size() <= 0?3:(mHeaderView == null ? gameList.size() :gameList.size() + 1);
	}
	
	@Override
	public int getItemViewType(int position) {
		if (gameList.size() <= 0) {
			return TYPE_EMPTY;
		}
		if (mHeaderView == null) {
			return TYPE_NORMAL;
		}
		if (position == 0){
			return TYPE_HEADER;
		}
		return TYPE_NORMAL;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	class MyEmptyViewHolder extends RecyclerView.ViewHolder{

	    public MyEmptyViewHolder(View itemView) {
	        super(itemView);
	        MyLog.d(TAG, "MyEmptyViewHolder");
	    }
	}
	
	
	@Override
	public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		if(viewType == TYPE_EMPTY){
			View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_game_item, parent, false);
			return new MyEmptyViewHolder(view);
		}
		 if(mHeaderView != null && viewType == TYPE_HEADER) return new ViewHolders(mHeaderView);
		View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_game_item, parent, false);
		MyLog.d(TAG, "onCreateViewHolder view : " + view.toString());
		return new ViewHolders(view);
	}

	@Override
	public void onBindViewHolder(final ViewHolder holder, final int position) {
		if (!(holder instanceof ViewHolders)){
			return;
		}
		{
		final ViewHolders holders = (ViewHolders) holder;
		
		holders.setMyPosition(position);
		if(getItemViewType(position) == TYPE_HEADER) return;
		final int currentPosition = getRealPosition(holders, position);
		final GameItem item = gameList.get(currentPosition);
		
		MyLog.d(TAG, "bitmap onBindViewHolder position : " + position + " currentPosition : " + currentPosition + ",name="+item.getTitle());

		holders.setGameId(item.getId());
		holders.setGameItem(item);
//		CommendItem ci = getGameCommend(item.getId());
//		if (ci != null)
//			commendMap.put(item.getId(), ci);
		holders.game_name_tv.setText(item.getActors());
		holders.game_desc_tv.setText(item.getTitle());
//		CommendItem commendItem = commendMap.get(item.getId());
		//MyLog.e(TAG, "commend map size="+commendMap.size());
//		if (commendItem != null) {
			//MyLog.d(TAG, "commendItem : " + commendItem);
			String uped = String.valueOf(item.getPraisecount());
			int userAction = item.getIsPraise();
			holders.detail_favour_tv.setText(uped);
			if (userAction == 0) {
				//holder.detail_favour_iv.setImageResource(R.drawable.favour_game_selector);
			} else if (userAction == 1) {
				//holder.detail_favour_iv.setImageResource(R.drawable.favoured_game);
			}
//		}else{
//			MyLog.d(TAG, "commendItem == null");
//		}

		String imageUrl = item.getImgurl();
		MyLog.d(TAG, "bitmap imageUrl :" + imageUrl + "  currentPosition=" + currentPosition + "holders="+holders);

		final String videoUrl = item.getVideourl();
		 MyLog.d(TAG, "videoUrl :" + videoUrl);
		 holders.game_cover_iv.setVisibility(View.INVISIBLE);
		 holders.game_cover_default_iv.setVisibility(View.VISIBLE);		
		 holders.game_cover_default_iv.setImageResource(R.drawable.loadng_icon);
		ImageLibrary.getInstance().getImageBitmap(context, imageUrl, new Callback() {

			@Override
			public void onImageDownloaded(final Bitmap bitmap,String imageUrlCb) {
				MyLog.e(TAG, "bitmap : " + bitmap + "  currentPosition=" + currentPosition + "holders="+holders);
				if (bitmap != null){
					GameItem item = holders.getGameItem();
					String image = item.getImgurl();
					if (image == null)
						return;
					if(image.equals(imageUrlCb)){
						MyLog.e(TAG, "bitmap imageUrlCb ... " + "imageUrl=" + image +" name="+item.getTitle());
						holders.game_cover_iv.setVisibility(View.VISIBLE);
						holders.game_cover_default_iv.setVisibility(View.INVISIBLE);
						holders.game_cover_iv.setImageBitmap(bitmap);
					}else{
						MyLog.e(TAG, "bitmap imageUrlCbERR ... " + "imageUrlCb=" + imageUrlCb +" name="+item.getTitle());
						MyLog.e(TAG, "bitmap imageUrlCbERR ... " + "imageUrl=" + image +" name="+item.getTitle());
					}
				}
			}
		});
		
		isDisplayUI(holders, item);

		// 设置回调接口
		holders.game_frame.setOnClickListener(new MyOnClickListener(currentPosition, holders));
		holders.game_play_pause_iv.setOnClickListener(new MyOnClickListener(currentPosition, holders));
		
		}
	}
	
	   public int getRealPosition(ViewHolders holder, int position) {
	        //int position = holder.getMyPosition();
	        return mHeaderView == null ? position : position - 1;
	    }

	/**
	 * //最新的游戏在一个月以内显示New字样
	 * @param holders
	 * @param item
	 */
	public static void isDisplayUI(ViewHolders holders,GameItem item) {
		//显示New字样
		String createTime = item.getCreatetime();
		createTime = DateTimeUtil.removeZoneTime(createTime);
		if(DateTimeUtil.isLessPreviousMonth(createTime)){
			holders.game_new_iv.setVisibility(View.VISIBLE);
		}else{
			holders.game_new_iv.setVisibility(View.INVISIBLE);
		}
		
		
		//显示VR or 2D图标
		boolean isVRFormat = GameItem.isVRFormat(item);
		boolean is2DFormat = GameItem.is2DFormat(item);
		if(isVRFormat){
			holders.game_vr_iv.setImageResource(R.drawable.vr_tag_big);
		}else if(is2DFormat){
			holders.game_vr_iv.setImageResource(R.drawable.nomal_tag_big);
		}
		
	}
	
	public class MyOnClickListener implements View.OnClickListener {
		private ViewHolders holder;
		private int position;
		private GameItem gameItem;
//		private CommendItem commendItem;

		public MyOnClickListener(int position, ViewHolders holder) {
			this.holder = holder;
			this.position = position;
//			if (position < gameList.size())
//				gameItem = gameList.get(position);
//			if (gameItem != null)
//				commendItem = commendMap.get(gameItem.getId());
		}

		@Override
		public void onClick(View v) {
			MyLog.d(TAG, "onClick position : " + position);
			if (position < gameList.size())
				gameItem = gameList.get(position);
//			if (gameItem != null)
//				commendItem = commendMap.get(gameItem.getId());
			switch (v.getId()) {
			case R.id.game_frame:
				MyLog.d(TAG, "game_frame is click...");
				if(isDismissed){
					EventBusUtils.videoDetailDialogCreate();
					 videoDetailDialog = new VideoDetailDialog(
							context, gameItem,
							R.style.FullScreen_Dialog_Tran,true);
					videoDetailDialog.show();
					videoDetailDialog.setOnDismissListener(dismissListener);
					MyDialogUtil.setDialogFullScreenGuide(context, videoDetailDialog);
					isDismissed = false;
				}
				break;
			case R.id.game_play_pause_iv:
				break;
			}
		}
	}
	
	
	public void onResume() {
		if (videoDetailDialog != null) {
			videoDetailDialog.onResume();
		}
		
		notifyDataSetChanged();

	}
	
	public void onPause() {
		if (videoDetailDialog != null) {
			videoDetailDialog.onPause();
		}

	}
	
	
	
	private boolean isDismissed = true;
	private OnDismissListener dismissListener = new OnDismissListener(){

		@Override
		public void onDismiss(DialogInterface dialog) {
			MyLog.d(TAG, "onDismiss...");
			EventBusUtils.videoDetailDialogDismiss();
			isDismissed = true;
		}
	};
	

	public static List<ViewHolders> isShowVideoList = new ArrayList<ViewHolders>();
	
	public static List<ViewHolders> getShowVideos(){
		return isShowVideoList;
	}
	
	
	private GameItem getGameCommend(int gameId) {
		return getGameCommend(gameId, false);
	}
	
	private GameItem getGameCommend(int gameId,boolean update) {
		MyLog.d(TAG, "getGameCommend gameId=" + gameId);
		GameItem citem = dataCenter.getGameCommend(gameId,update);
		if(citem == null){
			MyLog.d(TAG, "myDebug citem == null");
		}else{
			MyLog.d(TAG, "myDebug citem id : " + citem.getId());
		}
		return citem;
	
	}
	/**
	 * 上传赞或者踩
	 * 
	 * @param item
	 */

	private void uploadCommend(GameItem item) {
		dataCenter.setGameCommend(item.getId());
	}


	public class ViewHolders extends RecyclerView.ViewHolder {
		private TextView game_name_tv;
		private TextView game_desc_tv;

		private FrameLayout game_frame;
		private ImageView game_new_iv;
		private ImageView game_vr_iv;
		private ImageView game_cover_default_iv;
		private ImageView game_cover_iv;
		private ImageView detail_favour_iv;
		private TextView detail_favour_tv;
		private ImageView game_play_pause_iv;
		
		private GameItem gameItem;
		private int gameId;
		
		private int myPosition;
		
		
		
		public int getGameId() {
			return gameId;
		}

		public void setGameId(int gameId) {
			this.gameId = gameId;
		}
		
		

		public GameItem getGameItem() {
			return gameItem;
		}

		public void setGameItem(GameItem gameItem) {
			this.gameItem = gameItem;
		}
		

		public ImageView getGame_cover_iv() {
			return game_cover_iv;
		}

		public void setGame_cover_iv(ImageView game_cover_iv) {
			this.game_cover_iv = game_cover_iv;
		}

		public ImageView getGame_play_pause_iv() {
			return game_play_pause_iv;
		}

		public void setGame_play_pause_iv(ImageView game_play_pause_iv) {
			this.game_play_pause_iv = game_play_pause_iv;
		}

		public int getMyPosition() {
			return myPosition;
		}

		public void setMyPosition(int myPosition) {
			this.myPosition = myPosition;
		}

		public ViewHolders(View itemView) {
			super(itemView);
			
			if(itemView == mHeaderView) return;
			
			game_name_tv = (TextView) itemView.findViewById(R.id.game_name_tv);
			game_desc_tv = (TextView) itemView.findViewById(R.id.game_desc_tv);
			
			game_frame = (FrameLayout) itemView.findViewById(R.id.game_frame);
			game_new_iv = (ImageView) itemView.findViewById(R.id.game_new_iv);
			game_vr_iv = (ImageView) itemView.findViewById(R.id.game_vr_iv);
			game_cover_default_iv = (ImageView) itemView.findViewById(R.id.game_cover_default_iv);
			game_cover_iv = (ImageView) itemView.findViewById(R.id.game_cover_iv);

			detail_favour_iv = (ImageView) itemView.findViewById(R.id.detail_favour_iv);
			detail_favour_tv = (TextView) itemView.findViewById(R.id.detail_favour_tv);
			game_play_pause_iv = (ImageView) itemView.findViewById(R.id.game_play_pause_iv);

			//动态设置View高度，避免某类手机对图片压缩问题，使得图片始终保持16:9
			LayoutParams lp = game_frame.getLayoutParams();
			int screenMatch = DensityUtil.getScreenWidth(context);
			if(DensityUtil.isLandscape(context)){
				screenMatch = DensityUtil.getScreenHeight(context);
			}
			int gapDP = context.getResources().getDimensionPixelSize(R.dimen.padding_left_unify_game)*2;
			lp.height = (int) ((screenMatch - gapDP) * 9 /16);
			game_frame.setLayoutParams(lp);
		}
	}

	public List<GameItem> getGamelist() {
		return gameList;
	}

	// 单个更新数据
//	public void add(GameItem item) {
//		gameList.add(item);
//		CommendItem citem = getGameCommend(item.getId());
//		int gameId = item.getId();
//
//		if (citem == null) {
//			citem = new CommendItem();
//			citem.setId(gameId);
//
//		}
//		commendMap.put(gameId, citem);
//		notifyItemInserted(gameList.size() - 1);
//	}

//	public void add(GameItem item, int position) {
//		gameList.add(position, item);
//		CommendItem citem = getGameCommend(item.getId());
//
//		int gameId = item.getId();
//
//		if (citem == null) {
//			citem = new CommendItem();
//			citem.setId(gameId);
//		}
//		commendMap.put(gameId, citem);
//		notifyItemInserted(position);
//	}

	public void addList(List<GameItem> list,boolean isRefresh) {
		MyLog.d(TAG, "addList size : " + list.size() + "\naddList : " + list.toString());
		int oldcount = gameList.size();
		//如果未下拉数据添加到List顶端
		if(isRefresh){
			gameList.addAll(0, list);
		}else{
			gameList.addAll(list);
		}
		
		for (int i = 0;i<gameList.size();i++) {
			GameItem item = gameList.get(i);
			int gameId = item.getId();
			
			//当下拉刷新时候更新所有已存在的GameItem信息
			GameItem gameItemCur = GameItem.getGameById(gameId);
			gameList.set(i, gameItemCur);
//			CommendItem citem = getGameCommend(gameId,true);
//
//			if (citem == null) {
//				citem = new CommendItem();
//				citem.setId(gameId);
//			}
//			commendMap.put(gameId, citem);
			
		}
		
		MyLog.d(TAG, "gameList size : " + gameList.size() + " list : " + list.size());
		
//		if(isRefresh){
//			int position = 0;
//			if(ishaveHeader()){
//				position = 1;
//			}
//			notifyItemRangeInserted(position, list.size());
//		}else{
//			int positionStart = gameList.size() - list.size();
//			int itemCount = list.size();
//			if(ishaveHeader()){
//				positionStart = positionStart + 1;
//			}
//			notifyItemRangeInserted(positionStart < 0?0:positionStart,itemCount);
//		}
		
		//刷新list所有条目数据,以防数据更新(如修改名称或者点赞数据更新包含已加载和没加载的)
		int startPosition = 0;
		
		int itemCount = gameList.size();
		
		if(ishaveHeader()){
			
			startPosition = 1;
			
			itemCount = itemCount + 1;;
			
		}
		
		notifyItemRangeChanged(startPosition, itemCount);
		
	}


	/**
	 * 返回dialog的时候更新列表数据
	 * 
	 * @param position
	 * @param gameItem
	 * @param commendItem
	 */
//	public void refreshSingle(int position, GameItem gameItem, CommendItem commendItem) {
//		MyLog.d(TAG, "gameList indexOf: " + this.gameList.indexOf(gameItem));
//		MyLog.d(TAG, "commendItemList indexOf: " + this.commendItemList.indexOf(commendItem));
//		// this.gameList.remove(position);
//		// this.gameList.add(position, gameItem);
//		// this.commendItemList.remove(position);
//		// this.commendItemList.add(position, commendItem);
//		CommendItem old = commendMap.get(gameItem.getId());
//		if ((old.getDown() == commendItem.getDown()) && (old.getUp() == commendItem.getUp())
//				&& (old.getUserAction() == commendItem.getUserAction())) {
//			return;
//		}
//		commendMap.put(gameItem.getId(), commendItem);
//		notifyItemChanged(position);
//	}

	/**
	 * 批量更新数据
	 * 
	 * @param gameList
	 */
//	public void refreshData(List<GameItem> gameList) {
//		MyLog.d(TAG, "refreshData...gameList size : " + gameList.size());
//		this.gameList.addAll(gameList);
//		for (GameItem item : gameList) {
//			int gameId = item.getId();
//
//			if (!commendMap.containsKey(gameId)) {
//				CommendItem ci = new CommendItem();
//				ci.setId(gameId);
//				commendMap.put(gameId, ci);
//			}
//		}
//		// getBrowserCounts(gameList,-1);// -1 区分批量更新还是单独更新数据
//		notifyDataSetChanged();// 为了防止观看次数数据更新失败，在此先刷新显示列表
//	}

	/**
	 * 单独更新一条数据
	 *
	 */
	/*
	 * public void refreshData(GameItem gameItem,int position){
	 * getBrowserCounts(gameList,position); }
	 */

	public void remove(GameItem item) {
		int position = gameList.indexOf(item);
		gameList.remove(position);
		notifyItemRemoved(position);
	}

	@Override
	public void onViewDetachedFromWindow(ViewHolder holder) {
		super.onViewDetachedFromWindow(holder);
		ViewHolders holders = null;
		if(holder instanceof ViewHolders){
			holders = (ViewHolders) holder;
			MyLog.d(TAG, "onViewDetachedFromWindow item position : " + holders.getMyPosition()+" gameid="+holders.getGameId());
			if(getItemViewType(holders.getMyPosition()) == TYPE_HEADER) return;
		}else{
			return;
		}
		//boolean isShowingVideo = holders.svrVideoView.isShowingVideo();
		//if (isShowingVideo){
			//holder.svrVideoView.stopVideo();
		//	notPlayingUI(holders);
		//}
		//dataCenter.delCommendEventListener(KEY+holder.toString());
		viewHolderMap.remove(holders.getGameId());
		//MyLog.d(TAG, "detached viewHolderMap size=" + viewHolderMap.size()+" key="+KEY+holder.toString());
		super.onViewDetachedFromWindow(holder);
	}


	@Override
	public void onViewAttachedToWindow(ViewHolder holder) {
		//dataCenter.addCommendEventListener(listener, holder, KEY+holder.toString());
		
		ViewHolders holders = null;
		if(holder instanceof ViewHolders){
			holders = (ViewHolders) holder;
			MyLog.d(TAG, "onViewAttachedToWindow item position : " + holders.getMyPosition()+ " gameid="+holders.getGameId());
			if(getItemViewType(holders.getMyPosition()) == TYPE_HEADER) return;
		}else{
			return;
		}
		viewHolderMap.put(holders.getGameId(), holders);
		EventBusUtils.onGameListViewAttachedToWindow(holders.getMyPosition());
		super.onViewAttachedToWindow(holder);
	}
}
